package com.boruan.qq.zxgylibrary.ui.activities;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.boruan.qq.zxgylibrary.R;
import com.boruan.qq.zxgylibrary.R2;
import com.boruan.qq.zxgylibrary.base.BaseOneActivity;
import com.boruan.qq.zxgylibrary.constants.ConstantInfo;
import com.boruan.qq.zxgylibrary.constants.MyApplication;
import com.boruan.qq.zxgylibrary.service.model.AddressBackPriceBean;
import com.boruan.qq.zxgylibrary.service.model.AddressListBean;
import com.boruan.qq.zxgylibrary.service.presenter.AddressPresenter;
import com.boruan.qq.zxgylibrary.service.view.AddressView;
import com.boruan.qq.zxgylibrary.utils.CButtonUtils;
import com.boruan.qq.zxgylibrary.utils.CustomDialogOne;
import com.convenient.qd.core.base.arouter.ARouterConstant;
import com.convenient.qd.core.base.eventbus.Event;
import com.convenient.qd.core.base.eventbus.EventBusUtils;
import com.convenient.qd.core.user.UserDBHelper;
import com.convenient.qd.core.widget.AddressMessageEvent;
import com.convenient.qd.core.widget.SelfDialog;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by 崔琦 on 2019/8/12.
 * des: 添加地址页面
 */
@Route(path = ARouterConstant.ACTIVITY_ADD_HOME)
public class AddAddressActivity extends BaseOneActivity implements AddressView {
    @BindView(R2.id.tv_address_title)
    TextView tvAddressTitle;
    @BindView(R2.id.edt_input_name)
    EditText edtInputName;
    @BindView(R2.id.rb_boy)
    RadioButton rbBoy;
    @BindView(R2.id.rb_girl)
    RadioButton rbGirl;
    @BindView(R2.id.rg_boy_girl)
    RadioGroup rgBoyGirl;
    @BindView(R2.id.edt_input_phone)
    EditText edtInputPhone;
    @BindView(R2.id.select_address)
    TextView selectAddress;
    @BindView(R2.id.edt_input_address)
    EditText edtInputAddress;
    @BindView(R2.id.btn_save)
    Button btnSave;
    @BindView(R2.id.delete_address)
    TextView deleteAddress;
    @BindView(R2.id.rb_family)
    RadioButton rbFamily;
    @BindView(R2.id.rb_company)
    RadioButton rbCompany;
    @BindView(R2.id.rb_school)
    RadioButton rbSchool;
    @BindView(R2.id.rg_tag)
    RadioGroup rgTag;
    @BindView(R2.id.cb_default_address)
    CheckBox cbDefaultAddress;


    /**
     * 判断是修改还是删除
     */
    private String mType;
    private AddressPresenter addressPresenter;
    public static String cityName = "";
    /**
     * 列表页数据传递
     */
    private int addressId;
    private String userName;
    private String userPhone;
    private String address;
    private String detailAddress;
    private String fullAddress;
    private int sex;
    private int isDefault;
    private int tag;
    /**
     * 加载中dialog
     */
    private CustomDialogOne customDialog;
    /**
     * 选择地址时传过来的经纬度
     */
    private double lat;
    private double lng;
    private String addressProvinceCityArea;//只保存省市区不做展示用，只是后台统计需要。
    /**
     * 判断是新地址还是老地址
     */
    private boolean isOldAddress;

    private String adCode;

    private boolean isFromShuiChan;

    @Override
    protected int getLayoutId() {
        return R.layout.drug_activity_add_address;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        //没嵌入的时候调试用的，用application的为null
        /*SharedPreferences mSharedPreferences = getSharedPreferences("baseInfo",  Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = mSharedPreferences.edit();*/

        SharedPreferences.Editor editor = MyApplication.getSharedreferences().edit();
        editor.putString("user", UserDBHelper.getInstance().getAccessToken());
        editor.apply();

        if (getIntent() != null) {
            mType = getIntent().getStringExtra("type");
            isFromShuiChan = getIntent().getBooleanExtra("isFromShuiChan",false);
            if ("add".equals(mType)) {
                deleteAddress.setVisibility(View.GONE);
                tvAddressTitle.setText("新增地址");
            } else {
                deleteAddress.setVisibility(View.VISIBLE);
                addressId = getIntent().getIntExtra("addressId", 0);
                userName = getIntent().getStringExtra("userName");
                userPhone = getIntent().getStringExtra("userPhone");
                addressProvinceCityArea = getIntent().getStringExtra("address");
                detailAddress = getIntent().getStringExtra("detailAddress");
                fullAddress = getIntent().getStringExtra("fullAddress");
                isDefault = getIntent().getIntExtra("isDefault", 0);
                sex = getIntent().getIntExtra("sex", 0);
                tag = getIntent().getIntExtra("tag", 0);
                cityName = getIntent().getStringExtra("cityName");
                if (null != getIntent().getStringExtra("lat")) {
                    lat = Double.parseDouble(getIntent().getStringExtra("lat"));
                }
                if (null != getIntent().getStringExtra("lng")) {
                    lng = Double.parseDouble(getIntent().getStringExtra("lng"));
                }
                adCode = getIntent().getStringExtra("adCode");
                isOldAddress = getIntent().getBooleanExtra("isOldAddress", false);

                tvAddressTitle.setText("修改地址");
                edtInputName.setText(userName);
                edtInputPhone.setText(userPhone);

                if (isOldAddress) {//老地址
                    edtInputAddress.setText("");
                } else {
                    if (fullAddress.contains(detailAddress)) {
                        edtInputAddress.setText(fullAddress.replace(detailAddress, ""));
                    } else {
                        edtInputAddress.setText(detailAddress);
                    }
                    selectAddress.setText(detailAddress);
                    selectAddress.setTextColor(getResources().getColor(R.color.textColor));
                }

                if (sex == 1) {
                    rbBoy.setChecked(true);
                } else if (sex == 2) {
                    rbGirl.setChecked(true);
                }

                if (tag == 1) {
                    rbFamily.setChecked(true);
                } else if (tag == 2) {
                    rbCompany.setChecked(true);
                } else if (tag == 3) {
                    rbSchool.setChecked(true);
                }

                if (isDefault == 1) {
                    cbDefaultAddress.setChecked(true);
                }
            }
        }

        customDialog = new CustomDialogOne(this, R.style.CustomDialogOne);
        addressPresenter = new AddressPresenter(this);
        addressPresenter.onCreate();
        addressPresenter.attachView(this);

    }

    @OnClick({R2.id.iv_back, R2.id.select_address, R2.id.btn_save, R2.id.delete_address})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.iv_back) {
            finish();

        } else if (i == R.id.select_address) {
            Intent intent = new Intent(AddAddressActivity.this, LocationFromMapActivity.class);
            startActivityForResult(intent, 20);

        } else if (i == R.id.btn_save) {
            String userName = edtInputName.getText().toString().trim();
            String userPhone = edtInputPhone.getText().toString().trim();
            String userAddress = selectAddress.getText().toString().trim();
            String detailAddress = edtInputAddress.getText().toString().trim();
            if (!TextUtils.isEmpty(userName)) {
                if(userName.length() > 15 || userName.length() < 2){
                    Toast.makeText(this, "收货人姓名只支持中文、数字和字母的2-15个字符!", Toast.LENGTH_SHORT).show();
                    return;
                }
            } else {
                Toast.makeText(this, "请输入您的姓名！", Toast.LENGTH_SHORT).show();
                return;
            }
            if ("".equals(userPhone) || !addressPresenter.isMobile(userPhone)) {
                Toast.makeText(this, "手机号不合法，请重新输入！", Toast.LENGTH_SHORT).show();
            } else if ("选择收货地址".equals(userAddress)) {
                Toast.makeText(this, "请选择收货地址！", Toast.LENGTH_SHORT).show();
            } else if ("".equals(detailAddress)) {
                Toast.makeText(this, "请输入详细地址！", Toast.LENGTH_SHORT).show();
            } else {
                String fullAddress = userAddress + detailAddress;
                if (rbBoy.isChecked()) {
                    sex = 1;
                } else {
                    sex = 2;
                }

                if (rbFamily.isChecked()) {
                    tag = 1;
                } else if (rbCompany.isChecked()) {
                    tag = 2;
                } else if (rbSchool.isChecked()) {
                    tag = 3;
                }

                if (cbDefaultAddress.isChecked()) {
                    isDefault = 1;
                } else {
                    isDefault = 2;
                }
                if (!CButtonUtils.isFastDoubleClick(R.id.tv_commit_order)) {
                    if ("add".equals(mType)) {
                        addressPresenter.addAddress(userName, userPhone, addressProvinceCityArea, userAddress, fullAddress, isDefault, sex, cityName, tag, lat, lng, adCode);
                    } else {
                        addressPresenter.modifyAddressInfo(addressId, sex, userName, userPhone, addressProvinceCityArea, userAddress, fullAddress, isDefault, cityName, tag, lat, lng, adCode);
                    }
                } else {
                    Toast.makeText(this, "请不要过快点击！", Toast.LENGTH_SHORT).show();
                }

            }

        } else if (i == R.id.delete_address) {
            final SelfDialog selfDialog = new SelfDialog(AddAddressActivity.this, "提示", "确定要删除地址吗？", 1);
            selfDialog.setConfirmOnclickListener("确定", new SelfDialog.onConfirmOnclickListener() {
                @Override
                public void onConfirmClick() {
                    selfDialog.dismiss();
                    addressPresenter.deleteAddress(addressId);
                }
            });
            selfDialog.setNoOnclickListener("取消", new SelfDialog.onNoOnclickListener() {
                @Override
                public void onNoClick() {
                    selfDialog.dismiss();
                }
            });
            selfDialog.show();

            /*new CommonDialog.Builder(AddAddressActivity.this).setCanceledOnTouchOutside(false)
                    .setTitle("友情提示")
                    .setMessage("确定要删除地址吗？")
                    .setPositiveButton("确定", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            addressPresenter.deleteAddress(addressId);
                        }
                    }).setNegativeButton("取消", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                }
            }).show();*/

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 20 && resultCode == 22) {
            lat = data.getDoubleExtra("lat", 0);
            lng = data.getDoubleExtra("lon", 0);
            String mAddress = data.getStringExtra("address");
            String mProvince = data.getStringExtra("province");
            String mCity = data.getStringExtra("city");
            String mArea = data.getStringExtra("area");
            adCode = data.getStringExtra("adCode");
            addressProvinceCityArea = mProvince + " " + mCity + " " + mArea;
            Log.i("pca", addressProvinceCityArea);
            selectAddress.setText(mAddress);
            selectAddress.setTextColor(getResources().getColor(R.color.textColor));
        }
    }

    @Override
    public void showProgress() {
        customDialog.show();
    }

    @Override
    public void hideProgress() {
        customDialog.dismiss();
    }

    @Override
    public void addAddressSuccess(String msg) {
        /** 添加成功，返回列表页刷新 */
        Toast.makeText(this, "添加地址成功", Toast.LENGTH_SHORT).show();
        if(isFromShuiChan){
            EventBusUtils.sendEvent(new Event(1000, new AddressMessageEvent(
                    0,
                    isDefault,
                    edtInputName.getText().toString().trim(),
                    edtInputPhone.getText().toString().trim(),
                    addressProvinceCityArea,
                    selectAddress.getText().toString().trim(),
                    selectAddress.getText().toString().trim() + edtInputAddress.getText().toString().trim(),
                    adCode)));
        }
        setResult(11);
        finish();
    }

    @Override
    public void addAddressFailed(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void deleteAddressSuccess(String msg) {
        if (addressId == ConstantInfo.mAddressId) {//说明对已经选中的id执行了删除操作，提示用户更改地址
            ConstantInfo.isCurrentDelete = true;
        }
        /** 删除成功，返回列表页刷新 */
        Toast.makeText(this, "删除地址成功！", Toast.LENGTH_SHORT).show();
        setResult(12);
        finish();
    }

    @Override
    public void deleteAddressFailed(String msg) {
        if (TextUtils.isEmpty(msg)) {
            return;
        }
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();

    }

    @Override
    public void modifyAddressSuccess(String msg) {
        Toast.makeText(this, "修改地址成功！", Toast.LENGTH_SHORT).show();
        setResult(12);
        finish();
    }

    @Override
    public void modifyAddressFailed(String msg) {
        if (TextUtils.isEmpty(msg)) {
            return;
        }
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();

    }

    @Override
    public void getAddressListSuccess(List<AddressListBean.ResultBean> addressListBean) {

    }

    @Override
    public void getAddressListFailed(String msg) {

    }

    @Override
    public void addressBackPriceSuccess(AddressBackPriceBean.ResultBean addressBackPriceBean, int addressId, String fullAddress, String userInfo) {

    }

    @Override
    public void addressBackPriceFailed(String msg) {

    }

    @Override
    public void modifyDefaultAddressSuccess(String msg) {

    }

    @Override
    public void modifyDefaultAddressFailed(String msg) {

    }

}
